package com.magic.himalaya;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager.widget.ViewPager;

import com.magic.himalaya.adapters.IndicatorApdater;
import com.magic.himalaya.adapters.MainContentAdapter;
import com.magic.himalaya.interfaces.IPlayViewCallBack;
import com.magic.himalaya.presenters.AlbumDetailPresenter;
import com.magic.himalaya.presenters.PlayerPresenter;
import com.magic.himalaya.presenters.RecommendPresenter;
import com.magic.himalaya.utils.Constants;
import com.magic.himalaya.utils.LogUtil;
import com.magic.himalaya.views.PlayerListPopupWindow;
import com.squareup.picasso.Picasso;
import com.ximalaya.ting.android.opensdk.datatrasfer.CommonRequest;
import com.ximalaya.ting.android.opensdk.model.album.Album;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends FragmentActivity implements IPlayViewCallBack, PlayerListPopupWindow.OnClickPlayerListItemListener {

    private String TAG = "MainActivity";
    //内容显示组件
    private ViewPager index_viewPager;
    //导航标签栏组件
    private MagicIndicator magicIndicator;
    private ArrayList<String> categoryListData = new ArrayList<>();
    //导航栏上方的内容适配器
    private IndicatorApdater mIndicatorApdater;
    private ImageView mImage_view;
    private TextView mText_title;
    private TextView mText_announer;
    private ImageView mPlayer_start_pause;
    private ImageView mPlayer_list;
    private PlayerPresenter mPlayerPresenter;
    private Track mTrack;
    private View mClick_to_player;//点击区域进入播放器
    private PlayerListPopupWindow mPlayerListPopupWindow;
    private RecommendPresenter mRecommendPresenter;
    private AlbumDetailPresenter mAlbumDetailPresenter;
    private Album mAlbum;   //推荐列表的第一个专辑
    private List<Track> mTrackList = new ArrayList<>();//第一个专辑的所有声音
    private ImageView mBtn_search;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        initView();
        initPlayer();
    }

    /**
     * 初始化主页面整个框架组件==获得组件
     */
    private void init() {
        index_viewPager = findViewById(R.id.index_viewPager);//获取内容显示组件

        magicIndicator = findViewById(R.id.index_indicator);//获取导航栏组件

        mImage_view = findViewById(R.id.cover_url_small);//声音的封面
        mText_title = findViewById(R.id.track_title);//声音的标题
        mText_announer = findViewById(R.id.track_announer);//此声音专辑的作者昵称
        mPlayer_start_pause = findViewById(R.id.player_start_pause);//播放暂停按钮
        mPlayer_list = findViewById(R.id.player_list);//声音列表按钮
        mClick_to_player = findViewById(R.id.click_me_to_player);//点击进入播放器页面的触摸区域
        mBtn_search = findViewById(R.id.btn_image_search);//搜索按钮

        mPlayerPresenter = PlayerPresenter.getInstance();//获得播放器逻辑层实例化
        mRecommendPresenter = RecommendPresenter.getInstance();//获得推荐逻辑层实例化
        mAlbumDetailPresenter = AlbumDetailPresenter.getInstance();//获得专辑详情页的实例化

        mPlayerListPopupWindow = new PlayerListPopupWindow();//获得播放器列表实例化

        CommonRequest.getInstanse().setUseHttps(true);//设置获取数据方式为Https模式
    }

    /**
     * 进行主页面初始化,将导航栏进行初始化渲染处理
     * 再将内容区域进行初始化渲染处理
     */
    private void initView() {

        magicIndicator.setBackgroundColor(this.getResources().getColor(R.color.main_color, getTheme()));//设置导航栏背景颜色
        CommonNavigator commonNavigator = new CommonNavigator(this);//创建导航栏标签组件
        commonNavigator.setAdjustMode(true);//自我调节水平平分位置
        mIndicatorApdater = new IndicatorApdater(MainActivity.this);//创建导航栏标签适配器
        commonNavigator.setAdapter(mIndicatorApdater);//给导航栏标签设置适配器，用于展示导航栏内容
        magicIndicator.setNavigator(commonNavigator);//将导航栏标签设置在导航栏里
        {
            //初始化跑马灯效果
            mText_title.setSelected(true);//设置获得焦点，否则无法滚动
            mText_title.setEllipsize(TextUtils.TruncateAt.MARQUEE);//设置字体滚动效果
            mText_title.setHorizontallyScrolling(true);
            mText_title.setMarqueeRepeatLimit(-1);
            //初始化跑马灯效果
            mText_announer.setSelected(true);//设置获得焦点，否则无法滚动
            mText_announer.setEllipsize(TextUtils.TruncateAt.MARQUEE);//设置字体滚动效果
            mText_announer.setHorizontallyScrolling(true);
            mText_announer.setMarqueeRepeatLimit(-1);
        }

        //创建内容适配器并设置，viewPager初始化所需如下
        FragmentManager supportFragmentManager = getSupportFragmentManager();
        MainContentAdapter mainContentAdapter = new MainContentAdapter(supportFragmentManager, 0);
        index_viewPager.setAdapter(mainContentAdapter);

        ViewPagerHelper.bind(magicIndicator, index_viewPager);//将导航栏和显示内容的viewPager绑定


        initEvent();//初始化事件
    }

    /**
     * 初始化底部的迷你播放器,刚进来的时候如果播放列表没有声音。点击播放按钮会播放第一个专辑的声音
     */
    private void initPlayer() {
        if (mPlayerPresenter.isPlaying()) {
            mImage_view.setImageResource(R.drawable.selector_press_player_pause);//设置成暂停按钮
        } else {
            mPlayer_start_pause.setImageResource(R.drawable.selector_press_player_play);//设置成播放按钮
        }
        initData();//初始化数据
        //点击显示播放列表(PopupWindow窗口)
        mPlayer_list.setOnClickListener(v -> {
            mPlayerListPopupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
            mPlayerPresenter.playList();//显示播放列表
            //处理一下背景，将背景变暗
            setBgAlpha(0.6f);
        });
        //关闭播放列表(PopupWindow窗口)时,恢复播放器背景颜色
        mPlayerListPopupWindow.setOnDismissListener(() -> setBgAlpha(1.0f));
        mPlayerListPopupWindow.setOnClickPlayerListItemListener(this);//当播放列表里点击了声音后进行指定位置切歌


        //初始化播放器列表没有声音 点击播放时进行的操作
        mAlbum = mRecommendPresenter.getDataListByFirst();
        mRecommendPresenter.setOnInitDataListener(album -> mAlbum = album);//如果推荐列表刷新结束，则会获得推荐列表的第一个专辑
        LogUtil.d(TAG, mAlbum + ":::");
        if (!mPlayer_start_pause.hasOnClickListeners() && mTrack == null) {//首次初始化设置点击事件,
            mPlayer_start_pause.setOnClickListener(v -> {
                if (mAlbum != null) {
                    LogUtil.d(TAG, mAlbum.getTracks() + "");
                    mAlbumDetailPresenter.getAlbumDetail(mAlbum.getId(), 1);//请求逻辑层获取专辑内的数据
                    mAlbumDetailPresenter.setOnMainActivityListener(trackList -> {
                        mTrackList.clear();
                        mTrackList.addAll(trackList);
                        mPlayerPresenter.setMTracks(trackList, 0);//从第一个在专辑的第一个声音开始播放
                        mAlbumDetailPresenter.setOnMainActivityListener(null);
                    });
                }
            });
        }
    }

    /**
     * 初始化数据，如果没有找到当前正在播放的数据则不初始化播放器
     */
    private void initData() {
        mTrack = mPlayerPresenter.getTrackNotByPosition();
        LogUtil.d(TAG, ":::" + mTrack);
        if (mTrack != null) {
            if (mTrack.getCoverUrlSmall() != null && !mTrack.getCoverUrlSmall().trim().equals(""))
                Picasso.get().load(mTrack.getCoverUrlSmall()).into(mImage_view);//渲染图片
            mText_title.setText(mTrack.getTrackTitle());//渲染标题
            mText_announer.setText(mTrack.getAnnouncer().getNickname());//声音的作者昵称


            mPlayer_start_pause.setOnClickListener(v -> {
                if (mPlayerPresenter.isPlaying()) {
                    mPlayerPresenter.pause();
                } else {
                    mPlayerPresenter.play();
                }
            });
            mClick_to_player.setOnClickListener(v -> {
                //跳转至播放器
                startActivityForResult(new Intent(this, PlayerActivity.class), Constants.REQUEST_CODE);
            });
        }
    }

    /**
     * 设置播放器页面透明度，1.0完全不透明，0.0完全透明
     *
     * @param alpha
     */
    private void setBgAlpha(float alpha) {
        Window window = getWindow();
        WindowManager.LayoutParams windowAttributes = window.getAttributes();
        windowAttributes.alpha = alpha;
        window.setAttributes(windowAttributes);
    }


    /**
     * 初始化事件
     */
    private void initEvent() {
        //导航栏标签点击事件，进行切换ViewPager（Fragment）内容
        mIndicatorApdater.setOnIndicatorTapClickListener((int index) -> {
                    LogUtil.d(TAG, "点击改变了Fragment -----> " + index);
                    //点击的时候改变pager内容
                    index_viewPager.setCurrentItem(index);
                }
        );
        //设置播放器逻辑层的回调实现
        mPlayerPresenter.registerViewCallBack(this);
        mBtn_search.setOnClickListener(v -> {
            startActivityForResult(new Intent(this, SearchActivity.class), Constants.REQUEST_CODE);//跳转到搜索页面
        });//搜索按钮的点击事件
    }

    //===================== 以下为UI回调接口层实现

    @Override
    public void onPlayStart() {
        initData();
        mPlayer_start_pause.setImageResource(R.drawable.selector_press_player_pause);//设置成暂停按钮
    }

    @Override
    public void onPlayPause() {
        initData();
        mPlayer_start_pause.setImageResource(R.drawable.selector_press_player_play);//设置成播放按钮
    }

    @Override
    public void onPlayStop() {

    }

    @Override
    public void onError() {

    }

    @Override
    public void nextPlay(Track track) {
        initData();
    }

    @Override
    public void onPrePlay(Track track) {
        initData();
    }

    @Override
    public void onNowPlayTime(int time, int duration) {

    }

    @Override
    public void onPlayList(List<Track> trackList) {
        mPlayerListPopupWindow.setCurrentPlayerIndex(mPlayerPresenter.getCurrentIndex());//设置播放列表的播放位置
        mPlayerListPopupWindow.addPlayerList(trackList);    //添加播放列表里的声音
    }

    @Override
    public void onListLoaded(List<Track> trackList, int position) {

    }

    @Override
    public void onPlayModeChange(XmPlayListControl.PlayMode playMode) {

        switch (playMode) {
            case PLAY_MODEL_SINGLE://单曲播放
                mPlayerListPopupWindow.setPlayerMode(R.drawable.selector_press_player_status_single, "单曲播放");//设置popupwindow(播放列表)里面的播放模式
                break;
            case PLAY_MODEL_SINGLE_LOOP://单曲循环播放
                mPlayerListPopupWindow.setPlayerMode(R.drawable.selector_press_player_status_single_loop, "单曲循环");//设置popupwindow(播放列表)里面的播放模式
                break;
            case PLAY_MODEL_LIST://列表播放
                mPlayerListPopupWindow.setPlayerMode(R.drawable.selector_press_player_status_list, "列表播放");//设置popupwindow(播放列表)里面的播放模式
                break;
            case PLAY_MODEL_LIST_LOOP://列表循环
                mPlayerListPopupWindow.setPlayerMode(R.drawable.selector_press_player_status_list_loop, "列表循环");//设置popupwindow(播放列表)里面的播放模式
                break;
            case PLAY_MODEL_RANDOM://随机播放
                mPlayerListPopupWindow.setPlayerMode(R.drawable.selector_press_player_status_random, "随机播放");//设置popupwindow(播放列表)里面的播放模式
                break;
        }
    }

    @Override
    public void setViewData(Track track) {

    }

    @Override
    public void onAdLoading() {

    }

    @Override
    public void onAFinished() {

    }

    @Override
    public void toast(String str) {

    }


    //===================下面为PopupWindow的接口回调实现

    /**
     * 在播放器列表切歌时调用
     *
     * @param position
     */
    @Override
    public void switchPlaying(int position) {
        mPlayerPresenter.playByIndex(position);
    }

    /**
     * 在播放器列表切换播放模式调用
     */
    @Override
    public void switchPlayerMode() {
        mPlayerPresenter.switchPlayMode(mPlayerPresenter.getPlayMode());
    }

    @Override
    protected void onDestroy() {
//        mPlayerPresenter.stop();
        super.onDestroy();
    }
}